﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MotorcycleStore.Repository;
using MotorcycleStore.DomainModel;

namespace MotorcycleStore.MVC.Areas.Administration.Controllers
{
	public class CategoryController : Controller
	{
		ICategoryRepository repository;

		public CategoryController(ICategoryRepository repository)
		{
			this.repository = repository;
		}

		//
		// GET: /Administration/Category/

		public ActionResult Index()
		{
			var categories = repository.Categories.OrderBy(c => c.Name);

			return View(categories);
		}

		//
		// GET: /Administration/Category/Create

		public ViewResult Create()
		{
			return View();
		}

		//
		// POST: /Administration/Category/Create

		[HttpPost]
		public ActionResult Create(Category category)
		{
			if (repository.Categories.Any(c => c.Name == category.Name))
			{
				ModelState.AddModelError("Name", "A category already exists with this name");
			}

			if (ModelState.IsValid)
			{
				repository.Add(category);
				repository.Save();

				if (Request.IsAjaxRequest())
				{
					return PartialView("CategoryList", repository.Categories.OrderBy(c => c.Name));
				}

				TempData["MessageTitle"] = "Category Created";
				TempData["MessageContent"] =
					String.Format("The {0} category was created successfully", category.Name);

				return RedirectToAction("Index");
			}
			else if (Request.IsAjaxRequest())
			{
				Response.StatusCode = 500;
				return Content("Model error");
			}

			return View(category);
		}

		// GET: /Administration/Category/Delete/12

		public ViewResult Delete(int id)
		{
			var category = repository.Categories.SingleOrDefault(c => c.Id == id);
			if (category == null)
				return View("NotFound");

			return View(category);
		}

		[HttpPost]
		public ActionResult Delete(int id, string confirmDelete)
		{
			var category = repository.Categories.SingleOrDefault(c => c.Id == id);
			if (category == null)
				return View("NotFound");

			repository.Delete(id);
			repository.Save();

			TempData["MessageTitle"] = "Category Deleted";
			TempData["MessageContent"] = String.Format("The {0} category was deleted", category.Name);

			return RedirectToAction("Index");
		}
	}
}
